package cn.ardy.common.util.http;

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;


import qunar.QunarServer;
import qunar.hc.QunarClient;
import qunar.hc.tools.Strategies;

public class HttpUtil {
	private static final int TIME_OUT_IN_MILLSECONDS = 3000;
	private static final int CONN_TIMEOUT_IN_MILLISECONDS = 50;
	private static final int RETRY_TIMES = 2;
	
	private static final QunarClient httpClient;
	private static Logger log = Logger.getLogger(HttpUtil.class);
	static {
		HttpParams params = new BasicHttpParams();

		HttpConnectionParams.setConnectionTimeout(params,
				CONN_TIMEOUT_IN_MILLISECONDS);
		HttpConnectionParams.setSoTimeout(params, TIME_OUT_IN_MILLSECONDS);
		HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
		HttpProtocolParams
				.setUserAgent(params, "Chrome/5.0.342.9 Safari/533.2");

		HttpClientParams.setCookiePolicy(params,
				CookiePolicy.BROWSER_COMPATIBILITY);

		SchemeRegistry schemeRegistry = new SchemeRegistry();
		schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory
				.getSocketFactory()));

		ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(
				schemeRegistry);

		cm.setMaxTotal(200);
		cm.setDefaultMaxPerRoute(100);

		httpClient = new QunarClient(cm, params);
		Strategies.keepAlive(httpClient, 5000);

	}

	@SuppressWarnings("deprecation")
	public static String getContent(final String url) throws Exception {
		FutureTask<String> fu = new FutureTask<String>(new Callable<String>() {
			@Override
			public String call() throws Exception {
				String resultString = StringUtils.EMPTY;
				for (int i = 0; i < RETRY_TIMES; i++) {
					HttpGet request = new HttpGet(url);
					HttpResponse response = httpClient.execute(request);
					HttpEntity entity = null;
					try {
						entity = response.getEntity();
						StatusLine status = response.getStatusLine();
						if (status != null && status.getStatusCode() == 200) {
							resultString = EntityUtils
									.toString(entity, "UTF-8");
							return resultString;
						}
					} catch (Exception e) {
						log.warn(e.getMessage());
					} finally {
						EntityUtils.consume(entity);
						entity = null;
					}
				}
				return resultString;
			}
		});
		QunarServer.getExecutor().execute(fu);
		String content = fu.get(TIME_OUT_IN_MILLSECONDS, TimeUnit.MILLISECONDS);
		return content;
	}
}
